package com.project.forum.controller;

import com.project.forum.common.AppResult;
import com.project.forum.common.ResultCode;
import com.project.forum.config.AppConfig;
import com.project.forum.model.Article;
import com.project.forum.model.Board;
import com.project.forum.model.User;
import com.project.forum.services.IArticleService;
import com.project.forum.services.IBoradService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:发布新帖子
 * User:DELL
 * Time:18:55
 */
//发布新帖子
@Slf4j
@RequestMapping("/article")
@Api(tags = "文章接口")
@RestController
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoradService boradService;
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块Id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content){
        //检查用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState()==1){
            //用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //板块的校验
        Board board = boradService.selectById(boardId.longValue());
        if (board==null||board.getDeleteState()==1||board.getState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //返回响应
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //封装文章对象
        Article article=new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());//作者id
        //调用service启动代码
        articleService.create(article);
        //响应成功
        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块id")
                                                        @RequestParam(value = "boardId",required = false)
                                                        Long boardId){
        //定义返回的集合
        List<Article> articles=null;
        if (boardId==null){
            //查询所有
            articles = articleService.selectAll();
        }else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        //如果为空，则创建一个空集合
        if (articles==null){
            articles=new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }

    @ApiOperation("根据帖子Id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //从session中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用Service层获取帖子详情
        Article article = articleService.selectDetailById(id);
        //判断结果是否为空
        if (article==null){
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //判断当前用户是否为作者
        if (user.getId()==article.getUserId()){
            //是作者
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request, //获取当前登录的用户
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content){
        //获取当前登录的用户
        HttpSession session = request.getSession(false);//没有session不让创建
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if (user.getState()==1){
            //返回错误结果
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        if (article==null){
            //帖子不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断用户是不是作者
        if (user.getId()!=article.getUserId()){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子的状态
        if (article.getState()==1||article.getDeleteState()==1){
            //帖子结贴
            return AppResult.failed(ResultCode. FAILED_ARTICLE_BANNED);
        }
        //调用Service
        articleService.modify(id,title,content);
        //打印日志
        log.info("帖子更新成功. Article id ="+id+"user id"+user.getId()+".");
        //返回正确结果
        return AppResult.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                               @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if (user.getState()==1){
            //返回结果
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //调用Service
        articleService.thumbsUpById(id);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("删除帖子") @RequestParam("id") @NonNull Long id){
        //获取用户
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否禁言
        if (user.getState()==1){
            //返回结果
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        if (article==null||article.getDeleteState()==1){
            //帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //校验当前登录的用户是不是作者
        if (user.getId()!=article.getUserId()){
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用service，查询帖子详情
        articleService.deleteById(id);
        //返回操作成功
        return AppResult.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId){
        //如果UserId为空，则从session中获取当前登录的用户Id
        if (userId==null){
            //获取session
            HttpSession session = request.getSession(false);
            //获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId =user.getId();
        }
        //如果不为空，则从数据库中获取用户id,调用service
        List<Article> articles = articleService.selectByUserId(userId);
        //返回结果
        return AppResult.success(articles);
    }

}
